package com.ruoyi.web.controller.example;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.resturant.domain.ResShop;
import com.ruoyi.resturant.service.IResShopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@Anonymous
@RequestMapping("/api/redis")
@Api(tags = "Redis测试")
public class RedisController {
    //往Redis插入数据
    @Autowired
    private IResShopService resShopService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 根据店铺id查询店铺详情，并把店铺信息存入redis中
     * @params id 店铺id
     * @return
     */
    @ApiOperation("根据店铺id查询店铺详情，并把店铺信息存入Redis中")
    @ApiImplicitParam(name = "id", value = "店铺ID",
            required = true, dataType = "long", paramType = "path",
            dataTypeClass = Long.class)
    @GetMapping("/{id}")
    public AjaxResult setRedisObj(@PathVariable("id") Long id){
        ResShop resShop= resShopService.selectResShopById(id);
        String str=  JSON.toJSONString(resShop);
        redisCache.setCacheObject(String.valueOf(id),str,1, TimeUnit.HOURS);
        return AjaxResult.success(resShop);
    }

    /**
     * 根据店铺id从Redis取店铺的详情
     * @params id 店铺id
     * @return
     */
    @ApiOperation("根据店铺id从redis中查询店铺详情")
    @ApiImplicitParam(name = "id", value = "店铺ID",
            required = true, dataType = "long", paramType = "path",
            dataTypeClass = Long.class)
    @GetMapping("/ids/{id}")
    public AjaxResult getRedisObj(@PathVariable("id") Long id){
//        根据店铺id从redis取得详细的json字符串
       String str =  redisCache.getCacheObject(String.valueOf(id));
//       把店铺详情的json字符串转换为一个model对象resshop
        ResShop resShop= JSON.parseObject(str, ResShop.class);
        if (resShop !=null){
          resShop =resShopService.selectResShopById(id);
           String strDB=JSON.toJSONString(resShop);
           redisCache.setCacheObject(String.valueOf(id),str,1, TimeUnit.HOURS);
        }
//        返回取得的model对象
        return AjaxResult.success(resShop);
        }
}
